/*
 * Copyright 2002-2023 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.transaction.annotation;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.context.annotation.Role;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.lang.Nullable;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.config.TransactionManagementConfigUtils;
import org.springframework.transaction.event.TransactionalEventListenerFactory;
import org.springframework.util.CollectionUtils;

/**
 * Abstract base {@code @Configuration} class providing common structure for enabling
 * Spring's annotation-driven transaction management capability.
 *
 * @author Chris Beams
 * @author Stephane Nicoll
 * @since 3.1
 * @see EnableTransactionManagement
 */
@Configuration
public abstract class AbstractTransactionManagementConfiguration implements ImportAware {

	@Nullable
	protected AnnotationAttributes enableTx;

	/**
	 * Default transaction manager, as configured through a {@link TransactionManagementConfigurer}.
	 */
	@Nullable
	protected TransactionManager txManager;


	@Override
	public void setImportMetadata(AnnotationMetadata importMetadata) {
		this.enableTx = AnnotationAttributes.fromMap(
				importMetadata.getAnnotationAttributes(EnableTransactionManagement.class.getName()));
		if (this.enableTx == null) {
			throw new IllegalArgumentException(
					"@EnableTransactionManagement is not present on importing class " + importMetadata.getClassName());
		}
	}

	/**
	 * 当前函数setConfigurers在Spring Framework中的作用是注入并配置事务管理器的实现。
	 * 该函数通过@Autowired注解自动注入所有实现了TransactionManagementConfigurer接口的Bean，
	 * 并确保只有一个这样的Bean存在。如果存在多个实现，函数将抛出IllegalStateException异常。
	 * 如果只有一个实现，函数将调用其annotationDrivenTransactionManager()方法获取事务管理器，
	 * 并将其赋值给txManager变量，以便在后续的事务管理中使用。
	 * @Autowired(required = false)注解表示该注入是可选的，如果没有找到任何TransactionManagementConfigurer的实现，函数将直接返回，不会抛出异常。CollectionUtils.isEmpty(configurers)用于检查注入的集合是否为空，如果为空则直接返回。configurers.size() > 1检查集合中是否包含多个TransactionManagementConfigurer的实现，如果是则抛出异常。configurers.iterator().next()获取集合中的第一个元素，并调用其annotationDrivenTransactionManager()方法获取事务管理器，最后将其赋值给txManager变量。
	 * 该函数的核心逻辑是确保只有一个事务管理器的实现被注入，并将其配置为当前的事务管理器。这在实际业务中非常重要，因为它确保了事务管理的一致性和正确性，避免了多个事务管理器导致的冲突和不确定性。该函数通常在Spring的事务管理配置过程中被调用，确保事务管理器能够正确初始化并用于后续的事务操作。
	 * @param configurers
	 */
	@Autowired(required = false)
	void setConfigurers(Collection<TransactionManagementConfigurer> configurers) {
		if (CollectionUtils.isEmpty(configurers)) {
			return;
		}
		if (configurers.size() > 1) {
			throw new IllegalStateException("Only one TransactionManagementConfigurer may exist");
		}
		TransactionManagementConfigurer configurer = configurers.iterator().next();
		this.txManager = configurer.annotationDrivenTransactionManager();
	}


	@Bean(name = TransactionManagementConfigUtils.TRANSACTIONAL_EVENT_LISTENER_FACTORY_BEAN_NAME)
	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
	public static TransactionalEventListenerFactory transactionalEventListenerFactory() {
		return new RestrictedTransactionalEventListenerFactory();
	}

}
